<template>
  <div class="products-container">
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <ProductCard v-else v-for="item in products" :key="item.id" :product="item" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import ProductCard from './ProductCard.vue';
import { getProductList } from '@/api/product';

// 状态管理
const products = ref([]);//初始化空数组
const loading = ref(true);
const error = ref(null);

// 获取推荐商品数据
onMounted(async () => {
  loading.value = true;
  error.value = null;

  try {
    const response = await getProductList();
    if (response.code === 200 && response.data && Array.isArray(response.data.records)) {
      products.value = response.data.records;
    } else {
      products.value = [];
      error.value = '暂无商品数据';
    }
  } catch (err) {
    error.value = '加载商品失败，请稍后重试';
    products.value = [];
    console.error('获取推荐商品出错:', err);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.products-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 5列等宽 */
  gap: 24px;
  padding: 0 24px 24px 24px;
  box-sizing: border-box;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
  grid-column: 1 / -1;
}

.error {
  text-align: center;
  padding: 20px;
  color: #e63946;
  grid-column: 1 / -1;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .products-container {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 900px) {
  .products-container {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 600px) {
  .products-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 400px) {
  .products-container {
    grid-template-columns: 1fr;
  }
}
</style>
